<template>
  <div class="my-apps">
    <el-card class="app-list-card">
      <template #header>
        <div class="card-header">
          <span>我的应用</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :disabled="!selectedApps.length"
              @click="handleBatchStop"
            >
              停止选中
            </el-button>
            <el-button
              type="success"
              :disabled="!selectedApps.length"
              @click="handleBatchStart"
            >
              启动选中
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="appList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="应用" min-width="300">
          <template #default="{ row }">
            <div class="app-info">
              <el-image
                :src="row.icon"
                fit="cover"
                class="app-icon"
                :preview-src-list="[row.icon]"
              />
              <div class="app-details">
                <div class="app-name">{{ row.name }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期至" width="180">
          <template #default="{ row }">
            <div :class="['expiry-date', { 'expiring-soon': isExpiringSoon(row.expiryDate) }]">
              {{ formatDate(row.expiryDate) }}
              <el-tag v-if="isExpiringSoon(row.expiryDate)" type="danger" size="small">
                即将到期
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.status === 'running' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 'running' ? '停止' : '启动' }}
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleConfig(row)"
              >
                配置
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleRenew(row)"
              >
                续期
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="handleLogs(row)"
              >
                日志
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 续期对话框 -->
    <el-dialog
      v-model="renewDialogVisible"
      title="续期应用"
      width="400px"
    >
      <el-form :model="renewForm" label-width="100px">
        <el-form-item label="续期时长">
          <el-select v-model="renewForm.duration" placeholder="请选择续期时长">
            <el-option label="1个月" value="1" />
            <el-option label="3个月" value="3" />
            <el-option label="6个月" value="6" />
            <el-option label="12个月" value="12" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRenewConfirm">
            确认续期
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getInstalledAppList, startApp, stopApp } from '../../api/app'

const loading = ref(false)
const selectedApps = ref([])
const renewDialogVisible = ref(false)
const renewForm = ref({
  duration: '1',
  appId: null
})

// 模拟应用数据
const appList = ref([])
// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedApps.value = selection
}

const loadAppList = async () => {
  try {
    loading.value = true
    const response = await getInstalledAppList()
    console.log(response)
    appList.value = response || []
  } catch (error) {
    console.error('Failed to load app list:', error)
  } finally {
    loading.value = false
  }
}
onMounted(() => {
  loadAppList()
})
// 获取状态类型
const getStatusType = (status) => {
  const types = {
    running: 'success',
    stopped: 'info',
    error: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    running: '运行中',
    stopped: '已停止',
    error: '异常'
  }
  return texts[status] || status
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 检查是否即将到期（7天内）
const isExpiringSoon = (date) => {
  const daysLeft = dayjs(date).diff(dayjs(), 'day')
  return daysLeft <= 7 && daysLeft >= 0
}

// 格式化运行时长
const formatRunningTime = (seconds) => {
  if (seconds === 0) return '未运行'
  
  const days = Math.floor(seconds / (24 * 3600))
  const hours = Math.floor((seconds % (24 * 3600)) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  let result = []
  if (days > 0) result.push(`${days}天`)
  if (hours > 0) result.push(`${hours}小时`)
  if (minutes > 0) result.push(`${minutes}分钟`)
  
  return result.join(' ')
}

// 刷新列表
const handleRefresh = async () => {
  loading.value = true
  // 模拟刷新
  await new Promise(resolve => setTimeout(resolve, 1000))
  loading.value = false
  ElMessage.success('刷新成功')
}

// 批量启动
const handleBatchStart = async () => {
  try {
    loading.value = true
    await Promise.all(selectedApps.value.map(async (app) => {
      if (app.status !== 'running') {
        await new Promise(resolve => setTimeout(resolve, 1000))
        const index = appList.value.findIndex(item => item.id === app.id)
        if (index !== -1) {
          appList.value[index].status = 'running'
        }
      }
    }))
    ElMessage.success('批量启动成功')
  } finally {
    loading.value = false
  }
}

// 批量停止
const handleBatchStop = async () => {
  try {
    loading.value = true
    await Promise.all(selectedApps.value.map(async (app) => {
      if (app.status === 'running') {
        await new Promise(resolve => setTimeout(resolve, 1000))
        const index = appList.value.findIndex(item => item.id === app.id)
        if (index !== -1) {
          appList.value[index].status = 'stopped'
        }
      }
    }))
    ElMessage.success('批量停止成功')
  } finally {
    loading.value = false
  }
}

// 切换应用状态
const handleToggleStatus = async (app) => {
  try {
    loading.value = true
    if (app.status === 'running') {
      await stopApp(app.key)
    } else {
      await startApp(app.key)
    }
    const index = appList.value.findIndex(item => item.id === app.id)
    if (index !== -1) {
      appList.value[index].status = app.status === 'running' ? 'stopped' : 'running'
      ElMessage.success(`${app.status === 'running' ? '停止' : '启动'}成功`)
    }
  } finally {
    loading.value = false
  }
}

// 打开配置
const handleConfig = (app) => {
  ElMessage.info(`配置应用：${app.name}`)
}

// 打开续期对话框
const handleRenew = (app) => {
  renewForm.value.appId = app.id
  renewDialogVisible.value = true
}

// 确认续期
const handleRenewConfirm = async () => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    const index = appList.value.findIndex(item => item.id === renewForm.value.appId)
    if (index !== -1) {
      const months = parseInt(renewForm.value.duration)
      appList.value[index].expiryDate = dayjs()
        .add(months, 'month')
        .format('YYYY-MM-DD')
      ElMessage.success('续期成功')
      renewDialogVisible.value = false
    }
  } finally {
    loading.value = false
  }
}

// 查看日志
const handleLogs = (app) => {
  ElMessage.info(`查看应用日志：${app.name}`)
}
</script>

<style scoped>
.my-apps {
  padding: 20px;
}

.system-monitor-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 10px;
}

.monitor-item {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
}

.monitor-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.chart-container {
  height: 200px;
  width: 100%;
}

.monitor-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
}

.monitor-info .value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.monitor-info .label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.app-list-card {
  margin-bottom: 20px;
}

.app-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.app-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
}

.app-details {
  flex: 1;
  min-width: 0;
}

.app-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.app-description {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.expiry-date {
  display: flex;
  align-items: center;
  gap: 8px;
}

.expiring-soon {
  color: #e63c3c;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
